package io;

import java.io.*;

public class BufferedStreamDemo {
    public static void main(String[] args) {
        String largeFile = "large_file.txt";

        // 1. 缓冲字节流
        try (BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(largeFile));
             BufferedOutputStream bos = new BufferedOutputStream(
                     new FileOutputStream("copy_large_file.txt"))) {

            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int bytesRead;
            long start = System.currentTimeMillis();

            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            // 缓冲输出流需要刷新或关闭才会写入磁盘
            bos.flush();

            long end = System.currentTimeMillis();
            System.out.println("缓冲字节流复制耗时：" + (end - start) + "ms");

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 2. 缓冲字符流（提供便捷方法）
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream("poem.txt"), "UTF-8"));
             BufferedWriter bw = new BufferedWriter(
                     new OutputStreamWriter(
                             new FileOutputStream("copy_poem.txt"), "UTF-8"))) {

            String line;
            // 缓冲字符流特有方法：readLine()读取一行
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine(); // 写入换行符（跨平台兼容）
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
